package cn.tedu.weibo.controller;

import cn.tedu.weibo.response.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws Exception {
        //得到文件的原始名称
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        //得到文件名的后缀
        String suffix = fileName.substring(fileName.lastIndexOf('.'));
        //得到唯一文件名
        fileName = UUID.randomUUID()+suffix;
        System.out.println(fileName);
        String dirPath = "d:/files";
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String dataPath = sdf.format(new Date());
        File dirFile = new File(dirPath+dataPath);
        if (!dirFile.exists()){ //如果不存在则创建
            dirFile.mkdirs(); //创建文件夹
        }
        //得到完整的文件路径
        String filePath = dirPath+dataPath+fileName;
        //把文件保存到上面的路径   异常抛出
        file.transferTo(new File(filePath));
        //把图片路径响应给客户端
        return JsonResult.ok(dataPath+fileName);
    }
    @PostMapping("remove")
    public JsonResult remove(String imgUrl){
        new File("d:/files"+imgUrl).delete();
        return JsonResult.ok();
    }
}
